#include "DbSession.h"
#include <QDebug>
#include<QVariant>

#include <QMessageBox>
DbSession::DbSession()
{
    db = QSqlDatabase::addDatabase("QPSQL");
    db.setDatabaseName("dietsystem");
    db.setUserName("dietsystem");
    if( !db.open() ){
        QMessageBox::information( 0, "Unable to open database",
                                  db.lastError().databaseText() + "\nPlease read the README file in the sqltable directory for more information.");
     //   return 1;
    }
    else
    {
        qDebug() << "Base is open";
    }
}

QSharedPointer<User> DbSession::getUser(int id)
{
    qDebug()<<"In getUser";
    QSharedPointer<User> user = QSharedPointer<User>(new User);
    QSqlQuery query;
    query.prepare("SELECT * FROM users WHERE id=:id");
    query.bindValue(":id",id);
    query.exec();


     QSqlRecord rec = query.record();
     if (query.next()) {

         QString login1 = query.value(rec.indexOf("login")).toString();
qDebug() <<login1;
         QString token1 = query.value(rec.indexOf("token")).toString();
         user->setId(id);
         user->setLogin(login1);
         user->setToken(token1);
         user->setWeights(getWeights(id));

qDebug()<<user->getLogin();

     }
     else
     {

       //  user=NULL;
     }
     return user;
}

int DbSession::getUserIdByToken(QString token)
{
    int userId = 0;

    QString str = "SELECT *  FROM users WHERE "
                  "token = '" + token + "'";

    QSqlQuery query;

    query.exec(str);

    QSqlRecord rec = query.record();
    if (query.next()) {
        userId=query.value(rec.indexOf("id")).toInt();
    }

    return userId;
}

int DbSession::login(QString login1, QString password1)
{
    int userId=0;

    qDebug()<<"In login";
   QString str = "SELECT *  FROM users WHERE login = '"+ login1+ "'AND password ='"+password1+"'";

    QSqlQuery query;

    query.exec(str);

    QSqlRecord rec = query.record();
    if (query.next()) {
        QString str1 = query.value(rec.indexOf("login")).toString();
        userId=query.value(rec.indexOf("id")).toInt();
        qDebug() <<str1;

    }

    return userId;
}
QSharedPointer<QVector<QSharedPointer<Weight> > >  DbSession::getWeights(int id)
{


    QSharedPointer<QVector<QSharedPointer<Weight> > > vec =  QSharedPointer<QVector<QSharedPointer<Weight> > > (new QVector<QSharedPointer<Weight> >);

    QSqlQuery query;
    query.prepare("SELECT *  FROM weight WHERE userId = (:id1)");
    query.bindValue(":id1",id);
    query.exec();

    QSqlRecord rec = query.record();
qDebug()<<"In getWeights";
    while (query.next()) {
        double w1 = query.value(rec.indexOf("weight")).toDouble();
        QDate date1 = query.value(rec.indexOf("date1")).toDate();
qDebug()<<"fgvdfk";
        QSharedPointer<Weight> w = QSharedPointer<Weight>(new Weight);
        w->setWeight(w1);
        w->setDate(date1);
        vec->push_back(w);

    }

qDebug()<<vec->count();


    return vec;
}

QSharedPointer<QVector<QSharedPointer<User> > > DbSession::getAllUsers()
{
    QSharedPointer<QVector<QSharedPointer<User> > > vec =
            QSharedPointer<QVector<QSharedPointer<User> > > (new QVector<QSharedPointer<User> >);
    QSqlQuery query("SELECT * FROM users");
    QSqlRecord rec=query.record();
    while (query.next())
    {
        QSharedPointer<User> user = QSharedPointer<User>(new User);
        int id = query.value(rec.indexOf("id")).toInt();
        QString login= query.value(rec.indexOf("login")).toString();
        user->setId(id);
        user->setLogin(login);
        user->setWeights(getWeights(id));
        vec->push_back(user);
    }
qDebug()<<vec->count();

    return vec;
}

QSharedPointer<QVector<QSharedPointer<DietPlan> > > DbSession::getDietPlan(int userId)
{
    QSharedPointer<QVector<QSharedPointer<DietPlan> > > vec =
            QSharedPointer<QVector<QSharedPointer<DietPlan> > > (new QVector<QSharedPointer<DietPlan> >);


    QSqlQuery query;
    query.prepare("SELECT * FROM dietplan WHERE userId = (:id)");
    query.bindValue(":id", userId);
    query.exec();

    QSqlRecord rec = query.record();
 qDebug()<<"In getDietPlan";
    while (query.next()) {
        QSharedPointer<DietPlan> diet = QSharedPointer<DietPlan>(new DietPlan);
        int id = query.value(rec.indexOf("id")).toInt();
        QDate date1 = query.value(rec.indexOf("date1")).toDate();
        QString info = query.value(rec.indexOf("info")).toString();
qDebug()<<info;
        diet->setInfo(info);
        diet->setDate(date1);
        diet->setId(id);
        diet->setDietComments(getDietComments(id));

        vec->push_back(diet);
    }
    return vec;

}


QSharedPointer<QVector<QSharedPointer<FitnessPlan> > > DbSession::getFitnessPlan(int userId)
{
    QSharedPointer<QVector<QSharedPointer<FitnessPlan> > > vec =
            QSharedPointer<QVector<QSharedPointer<FitnessPlan> > > (new QVector<QSharedPointer<FitnessPlan> >);



    QSqlQuery query;
    query.prepare("SELECT * FROM fitnessplan WHERE userId = (:id)");
    query.bindValue(":id", userId);
    query.exec();

    QSqlRecord rec = query.record();
 qDebug()<<"In getFitnessPlan";
    while (query.next()) {
        QSharedPointer<FitnessPlan> fit = QSharedPointer<FitnessPlan>(new FitnessPlan);
        int id = query.value(rec.indexOf("id")).toInt();
        QDate date1 = query.value(rec.indexOf("date1")).toDate();
        QString info = query.value(rec.indexOf("info")).toString();
qDebug()<<info;
        fit->setInfo(info);
        fit->setDate(date1);
        fit->setId(id);
        fit->setFitnessComments(getFitnessComments(id));

        vec->push_back(fit);

    }
    return vec;

}

bool DbSession::isFreeLogin(QString login1)
{
    bool t=true;
    QString str = "SELECT *  FROM users WHERE login = '"+ login1+ "'";
    QSqlQuery query;
    query.exec(str);
    if (query.next()) {
        t=false;
    }
    return t;
}

bool DbSession::registerUser(QString login1, QString password1)
{
    if ((login1 == "") || (password1 == ""))
    {
        return false;
    }

    bool t=true;
    if (!isFreeLogin(login1))
    {
        t=false;
    }
    else
    {
        QString str = login1+password1;
        QSqlQuery query;
        query.prepare("INSERT INTO users (login, password, token) "
                      "VALUES (:login, :password, :token)");
        query.bindValue(":login", login1);
        query.bindValue(":password", password1);
        query.bindValue(":token", str);
        query.exec();
    }

    return t;

}

void DbSession::addWeight(int userId, double weight)
{
    QSqlQuery query;
    if (!isExistWeight(userId))

    {
    query.prepare("INSERT INTO weight(userid, weight, date1) "
                  "VALUES (:userid, :weight, :date)");
    query.bindValue(":userid", userId);
    query.bindValue(":weight", weight);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();
}
    else
    {
        qDebug()<<"Already existed";
        query.prepare("UPDATE weight SET weight=(:weight) WHERE userid=(:userid) AND date1= (:date)");
        query.bindValue(":weight", weight);
        query.bindValue(":userid", userId);
        query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
        query.exec();
    }
}

bool DbSession::isExistWeight(int userId)
{
    bool t=true;
    QSqlQuery query;
    query.prepare("SELECT * from weight WHERE  userid=(:userid) AND date1=(:date)");
    query.bindValue(":userid", userId);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();
if (!query.next())
    {
    t=false;

}
    return t;
}

bool DbSession::isExistDietPlan(int userId)
{
    bool t=true;
    QSqlQuery query;
    query.prepare("SELECT * from dietplan WHERE  userid=(:userid)");
    query.bindValue(":userid", userId);
    query.exec();
    qDebug()<<"UserId="<<userId;
if (!query.next())
    {
    t=false;
    qDebug()<<"Not Existed!!!";

}
    return t;
}


void DbSession::addDietPlan(int userId, QString dietplan)
{
    QSqlQuery query;

    query.prepare("INSERT INTO dietplan(userid, info, date1) "
                  "VALUES (:userid, :info, :date)");
    query.bindValue(":userid", userId);
    query.bindValue(":info", dietplan);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();

}

void DbSession::editDietPlan(int dietPlanId, QString dietplan)
{
    QSqlQuery query;
    query.prepare("UPDATE dietplan SET info=(:dietplan), date1=(:date) WHERE id=(:dietPlanId)");
    query.bindValue(":dietplan", dietplan);
    query.bindValue(":dietPlanId", dietPlanId);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();


}


bool DbSession::isExistFitnessPlan(int userId)
{
    bool t=true;
    QSqlQuery query;
    query.prepare("SELECT * from fitnessplan WHERE  userid=(:userid)");
    query.bindValue(":userid", userId);
    query.exec();
    qDebug()<<"UserId="<<userId;
if (!query.next())
    {
    t=false;
    qDebug()<<"Not Existed!!!";

}
    return t;
}


void DbSession::addFitnessPlan(int userId, QString fitnessplan)
{
    QSqlQuery query;

    query.prepare("INSERT INTO fitnessplan(userid, info, date1) "
                  "VALUES (:userid, :info, :date)");
    query.bindValue(":userid", userId);
    query.bindValue(":info", fitnessplan);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();

}

void DbSession::editFitnessPlan(int fitnessPlanId, QString fitnessplan)
{
    QSqlQuery query;
    query.prepare("UPDATE fitnessplan SET info=(:fitnessplan), date1=(:date) WHERE id=(:fitnessPlanId)");
    query.bindValue(":fitnessplan", fitnessplan);
    query.bindValue(":fitnessPlanId", fitnessPlanId);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();

    sortTableAsc("fitnessplan");

}




DbSession& DbSession::getInstance()
{
    static DbSession s;
    return s;
}

QSharedPointer<QVector<QSharedPointer<DietComment> > >  DbSession::getDietComments(int dietId)
{


    QSharedPointer<QVector<QSharedPointer<DietComment> > > vec =  QSharedPointer<QVector<QSharedPointer<DietComment> > > (new QVector<QSharedPointer<DietComment> >);

    QSqlQuery query;
    query.prepare("SELECT *  FROM dietcomments WHERE dietplanid = (:id1)");
    query.bindValue(":id1",dietId);
    query.exec();

    QSqlRecord rec = query.record();
qDebug()<<"In getDietComments";
    while (query.next()) {
        QString info1 = query.value(rec.indexOf("info")).toString();
        QDate date1 = query.value(rec.indexOf("date1")).toDate();
        int userId = query.value(rec.indexOf("userid")).toInt();
        int id = query.value(rec.indexOf("id")).toInt();
qDebug()<<"fgvdfk";
        QSharedPointer<DietComment> dietcomment = QSharedPointer<DietComment>(new DietComment);
        dietcomment->setInfo(info1);
        dietcomment->setDate(date1);
        dietcomment->setUserId(userId);
        dietcomment->setId(id);
       // dietcomment->setDietId(dietId);
        vec->push_back(dietcomment);

    }

qDebug()<<vec->count();


    return vec;
}




QSharedPointer<QVector<QSharedPointer<FitnessComment> > >  DbSession::getFitnessComments(int fitnessId)
{


    QSharedPointer<QVector<QSharedPointer<FitnessComment> > > vec =  QSharedPointer<QVector<QSharedPointer<FitnessComment> > > (new QVector<QSharedPointer<FitnessComment> >);

    QSqlQuery query;
    query.prepare("SELECT *  FROM fitnesscomments WHERE fitnessplanid = (:id1)");
    query.bindValue(":id1",fitnessId);
    query.exec();

    QSqlRecord rec = query.record();
qDebug()<<"In getFitnessComments"<<fitnessId;

    while (query.next()) {
        QString info1 = query.value(rec.indexOf("info")).toString();
        QDate date1 = query.value(rec.indexOf("date1")).toDate();
        int userId = query.value(rec.indexOf("userid")).toInt();
        int id = query.value(rec.indexOf("id")).toInt();
qDebug()<<"fgvdfk";
        QSharedPointer<FitnessComment> fitnesscomment = QSharedPointer<FitnessComment>(new FitnessComment);
        fitnesscomment->setInfo(info1);
        fitnesscomment->setDate(date1);
        fitnesscomment->setUserId(userId);
        fitnesscomment->setId(id);

        vec->push_back(fitnesscomment);

    }

qDebug()<<vec->count();


    return vec;
}

void DbSession::addDietComment(int DietPlanId, int userId, QString info)
{
    QSqlQuery query;

    query.prepare("INSERT INTO dietcomments(userid, dietplanid, info, date1) "
                  "VALUES (:userid, :dietplanid, :info, :date)");
    query.bindValue(":userid", userId);
    query.bindValue(":dietplanid", DietPlanId);
    query.bindValue(":info", info);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();
}

void DbSession::addFitnessComment(int FitnessPlanId, int userId, QString info)
{
    QSqlQuery query;

    query.prepare("INSERT INTO fitnesscomments(userid, fitnessplanid, info, date1) "
                  "VALUES (:userid, :fitnessplanid, :info, :date)");
    query.bindValue(":userid", userId);
    query.bindValue(":fitnessplanid", FitnessPlanId);
    query.bindValue(":info", info);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    query.exec();
}


void DbSession::sortTableAsc(QString nameTable)
{
    QString str="SELECT * FROM " +nameTable+" ORDER BY id";
    QSqlQuery query;
  /*  query.prepare("SELECT * FROM (:nameTable) ORDER BY id");
    query.bindValue(":nameTable", nameTable);*/
    query.exec(str);
    qDebug()<<"request:"<<str;
}

